package com.tigercel.xiangchengyun.ui.activities

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.Button
import com.bumptech.glide.Glide
import com.lljjcoder.Interface.OnCityItemClickListener
import com.lljjcoder.bean.DistrictBean
import com.lljjcoder.bean.ProvinceBean
import com.lljjcoder.citywheel.CityConfig
import com.lljjcoder.style.citypickerview.CityPickerView
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.tigercel.xiangchengyun.R
import com.tigercel.xiangchengyun.utils.Global
import com.tigercel.xiangchengyun.utils.JsonUtil
import com.tigercel.xiangchengyun.utils.PreferencesUtil
import kotlinx.android.synthetic.main.activity_account_setting.*
import kotlinx.android.synthetic.main.include_titlebar.*
import me.leefeng.promptlibrary.PromptDialog
import org.jetbrains.anko.toast
import java.io.File
import java.util.*


class AccountSettingActivity : AppCompatActivity() {
    internal var mCityPickerView = CityPickerView()
    private var localDatas: PreferencesUtil? = null
    private lateinit var selectList: MutableList<LocalMedia>
    val DATE_DIALOG = 1
    var mYear: Int = 0
    var mMonth: Int = 0
    var mDay: Int = 0
    private var setHeadDialog: Dialog? = null
    private var imagepath = ""
    private var mDialogView: View? = null
    private val mButton: Button? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_account_setting)
        mCityPickerView.init(this)
        localDatas = PreferencesUtil(this)
        titlebar_tv.text = "用户信息"
        titlebar_iv_left.visibility = View.VISIBLE
        titlebar_iv_left.setImageResource(R.drawable.btn_nav_back)
        titlebar_iv_left.setOnClickListener { sentDatas() }
        tv_phoneNum.text = localDatas!!.preferences["phone"]
        tv_user_nickname.text = localDatas!!.preferences["nickname"]
        tv_area.text = localDatas!!.preferences["area"]
        tv_country.text = localDatas!!.preferences["country"]
        tv_birthday.text = localDatas!!.preferences["birthday"]
        tv_sex.text = localDatas!!.preferences["sex"]
        imagepath = localDatas!!.preferences["userAvatar"]!!
        Glide.with(this).load(localDatas!!.preferences["userAvatar"]).into(img_userTx)
        re_country!!.setOnClickListener {
            val cityConfig = CityConfig.Builder().title("选择城市").build()//标题

            mCityPickerView.setConfig(cityConfig)
            mCityPickerView.setOnCityItemClickListener(object : OnCityItemClickListener() {
                @SuppressLint("SetTextI18n")
                override fun onSelected(province: ProvinceBean?, city: com.lljjcoder.bean.CityBean?, district: DistrictBean?) {
                    tv_country!!.text = province!!.name + "-" + city!!.name + "-" + district!!.name
                }

                override fun onCancel() {
                    super.onCancel()
                }
            })
            mCityPickerView.showCityPicker()

        }
        tv_phoneNum.text = localDatas!!.preferences["phone"]
        re_nickname.setOnClickListener {
            val intent = Intent()
            intent.setClass(this, ModifyNickNameActivity::class.java)
            startActivityForResult(intent, 1)
        }
        re_sex.setOnClickListener {
            val intent = Intent()
            intent.setClass(this, ModifySexActivity::class.java)
            startActivityForResult(intent, 2)
        }
        re_locate.setOnClickListener {
            val intent = Intent()
            intent.setClass(this, ModifyAreaActivity::class.java)
            startActivityForResult(intent, 3)
        }
        re_birthday.setOnClickListener {
            val calendar = Calendar.getInstance()
            mYear = calendar.get(Calendar.YEAR)
            mMonth = calendar.get(Calendar.MONTH)
            mDay = calendar.get(Calendar.DAY_OF_MONTH)
            showDialog(DATE_DIALOG)
        }
        img_end.setOnClickListener {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                    .theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                    .maxSelectNum(1)// 最大图片选择数量 int
//                    .minSelectNum()// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .previewVideo(true)// 是否可预览视频 true or false
                    .enablePreviewAudio(true) // 是否可播放音频 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
//                    .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                    .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                    .isGif(true)// 是否显示gif图片 true or false
//                    .compressSavePath(getPath())//压缩图片保存地址
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                    .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                    .openClickSound(false)// 是否开启点击声音 true or false
//                    .selectionMedia(selectList)// 是否传入已选图片 List<LocalMedia> list
                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                    .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                    .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
//                    .rotateEnabled() // 裁剪是否可旋转图片 true or false
//                    .scaleEnabled()// 裁剪是否可放大缩小图片 true or false
                    //.videoQuality(0)// 视频录制质量 0 or 1 int
                    .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                    .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                    .recordVideoSecond(60)//视频秒数录制 默认60s int
                    .isDragFrame(false)// 是否可拖动裁剪框(固定)
                    .forResult(PictureConfig.CHOOSE_REQUEST)
        }
        re_phone.setOnClickListener {
            val intent = Intent()
            intent.setClass(this, BindPhoneActivity::class.java)
            startActivityForResult(intent, 4)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && resultCode == 1) {

            val content = data!!.getStringExtra("data")
            tv_user_nickname.text = content
        } else if (requestCode == 2 && resultCode == 2) {
            val content = data!!.getStringExtra("data")
            tv_sex.text = content
        } else if (requestCode == 3 && resultCode == 3) {
            val content = data!!.getStringExtra("data")
            tv_area.text = content
        } else if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            selectList = PictureSelector.obtainMultipleResult(data)
            Log.e("图片地址", selectList[0].path)
            val file = File(selectList[0].path)
            imagepath = selectList[0].path
            Glide.with(this).load(file).into(img_userTx)
        } else if (requestCode == 4 && resultCode == 4) {
            val content = data!!.getStringExtra("data")
            tv_phoneNum.text = content
        }

    }

    override fun onCreateDialog(id: Int): Dialog? {
        when (id) {
            DATE_DIALOG -> return DatePickerDialog(this, mdateListener, mYear, mMonth, mDay)
        }
        return null
    }

    private val mdateListener = DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
        mYear = year
        mMonth = monthOfYear
        mDay = dayOfMonth
        display()
    }

    fun display() {
        tv_birthday.setText(StringBuffer().append(mYear).append("-").append(mMonth + 1).append("-").append(mDay).append(" "))
    }

    private fun sentDatas() {
        var progressDailog = PromptDialog(this)
        progressDailog.showLoading("信息更新中,请稍后...")
        var gender = ""
        if (tv_sex.text == "男") {
            gender = "1"
        } else {
            gender = "2"
        }
        OkGo.post<String>(Global.baseUrl + Global.modifyUserInfo)
                .tag(this)
                .params("token", localDatas!!.preferences["token"])
                .params("gender", gender)
                .params("nickname", tv_user_nickname.text.toString())
                .params("birth", tv_birthday.text.toString())
                .params("location", tv_country.text.toString())
                .params("address", tv_area.text.toString())
                .params("img", File(imagepath))
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        var result = response!!.body()
                        var status = JsonUtil.get_key_string("status", result)
                        var msg = JsonUtil.get_key_string("msg", result)
                        var code = JsonUtil.get_key_string("code", result)
                        var data = JsonUtil.getList("data", result)
                        if (status == "0") {
                            progressDailog.dismiss()
                            localDatas!!.modifyData(tv_user_nickname.text.toString(), imagepath, tv_sex.text.toString(), tv_birthday.text.toString(), tv_country.text.toString(), tv_area.text.toString(), tv_phoneNum.text.toString())
                            this@AccountSettingActivity.finish()
                        } else {
                            progressDailog.dismiss()
                            toast("用户信息修改失败")
                        }
                    }

                })
    }
}

